<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Main extends Backend_Controller {

	/**
	 * 显示后台首页布局
	 */
	public function index() {
		$this->load->model('backend/Model_model', 'Model');
		$data = $this->identity;
		$config['field'] = 'rank';
		$config['order_by'] = 'desc';
		$result = $this->Model->getModelAll($config, NULL);
		if (!empty($result['data'])) {
			$data['header'] = $this->getChild($result['data'], 0);
		}
		$this->load->view('backend/main/index', $data);
	}

	private function getChild($result, $parent = 0, $times = 0) {
		$header = '';
		foreach ($result as $v) {
			if ($v['parent'] == $parent) {
				switch ($times) {
					case 0:
						$tmp = $this->getChild($result, $v['id'], $times + 1);
						$header .= '<div class="accordionHeader"><h2><span>Folder</span>' . $v['name'] . '</h2></div>'
								. '<div class="accordionContent"><ul class="tree treeFolder">' . $tmp . '</div>';
						break;
					case 1:
						$tmp = $this->getChild($result, $v['id'], $times + 1);
						$header .= '<li><a href="javascript:void(0)">' . $v['name'] . '</a><ul>' . $tmp . '</ul></li>';
						break;
					case 2:
						$header .= '<li><a href="' . site_url($v['url']) . '" target="navTab" rel="' . $v['rel']
								. '">' . $v['name'] . '</a></li>';
						break;
				}
			}
		}
		return $header;
	}

	/**
	 * 退出
	 */
	public function logout() {
		$this->session->sess_destroy();
		redirect(site_url('backend/login/index'));
	}

	public function editable() {
		$this->load->library('form_validation');
		$this->form_validation->validateData(array(
			'db', 'value', 'primary', 'id'
		), array(
			array('db','required'),
			array('value', 'required'),
			array('primary', 'required'),
			array('id', 'integer|greater_than[0]')
		));
		if($this->form_validation->hasErrors()) {
			$this->renderJson(300, $this->form_validation->error);
		}
		$table = $field = '';
		sscanf($this->form_validation->db, '%[^.].%[^.]', $table, $field);
		if(!$table || !$field || !$this->db->table_exists($this->db->dbprefix($table)) || !$this->db->field_exists($field, $this->db->dbprefix($table))) {
			$this->renderJson(300, 'table:'.$table . ' field:'.$field. ' table_exists:' . $this->db->table_exists($this->db->dbprefix($table)));
		}
		$this->db->update($table, array($field=>  $this->form_validation->value), array($this->form_validation->primary =>  $this->form_validation->id));
		if($this->db->affected_rows() > 0) {
			$this->renderJson(200);
		}
		$this->renderJson(300);
	}
	
	public function notify() {
		$this->load->config('system_info');
		$this->load->model('backend/Order_model', 'Order');		
		$this->load->model('backend/Refund_model', 'Refund');
		$overtimePack = $this->Order->overtimePack(config_item('cfg_scheduled_overtime_o'));
		$refundPack = $this->Refund->refundPack();
		$this->renderJson(200, '', array('overtimePack'=>$overtimePack, 'refundPack'=>$refundPack));
	}
}
